<template>
    <div class="dj-form">
        <slot></slot>
    </div>
</template>
<script>
import emitter from '@/mixins/emitter.js'
export default {
  name: 'dj-form',
  mixins: [emitter],
  data () {
    return {
      fields: [],
      validValue: true
    }
  },
  props: {
    model: {
      type: Object,
      required: true
    },
    rules: {
      type: Object
    }
  },
  provide () {
    return {
      form: this
    }
  },
  created () {
    // 因为子组件先于父组件渲染 所以需要在父组件的created里监听子组件mounted里派发的事件
    this.$on('form-item-add', (field) => {
      if (field) this.fields.push(field)
    })
    this.$on('form-item-remove', (field) => {
      if (field.prop) this.fields.splice(this.fields.indexOf(field), 1)
    })
    this.$on('form-submit', () => {
      this.validate()
      this.$emit('submit', this.validValue)
    })
  },
  methods: {
    sayHelloWorld () {
      console.log('HelloWorld')
    },
    // 公开的重置方法
    resetFileds () {
      this.fields.forEach(field => {
        field.resetField()
      })
    },
    // 公开的验证方法
    validate (callback) {
      return new Promise((resolve, reject) => {
        this.validValue = true
        this.fields.forEach((filed, index) => {
          filed.validate('', error => {
            if (error) {
              this.validValue = false
            }
            if (index === this.fields.length - 1) {
            // 全部校验完成
              resolve(this.validValue)
              if (typeof callback === 'function') {
                callback(this.validValue)
              }
            }
          })
        })
      })
    }
  }
}
</script>
